package ldh.bean.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValidateHelp {

	private Map<Object, Exception> errors = new HashMap<Object, Exception>();
	
	private final static Logger logger = LoggerFactory.getLogger(ValidateHelp.class);
	
	public static ValidateHelp create() {
		return new ValidateHelp();
	}
	//不能为空
	public ValidateHelp notNull(String str) {
		if(str == null) {
			errors.put(str, new NullPointerException(str + " must not be null!"));
		}
		
		return this;
	}
	
	//不能为空
	public ValidateHelp notNull(Object obj) {
		if(!ValidateUtil.notNull(obj)) {
			errors.put(obj, new NullPointerException(obj + " must not be null!"));
		}
		return this;
	}
	
	//不能为空
	public ValidateHelp notEmpty(String str) {
		if(!ValidateUtil.notEmpty(str)) {
			errors.put(str, new NullPointerException(str + " must not be empty!"));
		}
		
		return this;
	}
	
	public ValidateHelp notEmpty(Object bean, String...properties) {
		this.notNull(bean);
		if (properties != null) {
			for (String property : properties) {
				String  methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
				Method method;
				try {
					method = bean.getClass().getMethod(methodName , null);
					Object o = method.invoke(bean, null);
					this.notNull(o);
				} catch (Exception e) {
				} 
				
			}
		}
		
		return this;
	}
	
	public boolean hasErrors() {
		return errors.size() > 0;
	}
	
	public Map<Object, Exception> getErrors() {
		return errors;
	}
	
	public void errors() {
		if (hasErrors()) {
			for (Entry<Object, Exception> entry : errors.entrySet()) {
				logger.error(entry.getValue().getMessage());
				System.out.println(entry.getValue());
			}
			throw new RuntimeException("ValidateHelp validate many errors!!!!!!");
		}
	}
}
